package 周赛._d_73;

import java.util.*;

public class _5217_将杂乱无章的数字排序 {
    public static void main(String[] args) {
        int[] mapping = new int[]{8,9,4,0,2,1,3,5,7,6};
        int[] nums = new int[]{991,338,38};

    }
    public int[] sortJumbled(int[] mapping, int[] nums) {
        Map<Character, Integer> map = new HashMap<>();
        for (char i = '0'; i <= '9'; i++) {
            map.put(i, mapping[i - '0']);
        }
        int[] temp = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            int reflect = 0;
            String target = String.valueOf(nums[i]);
            for (int j = 0; j < target.length(); j++) {
                reflect *= 10;
                char c = target.charAt(j);
                reflect += map.get(c);
            }
            temp[i] = reflect;
        }
        int[] ans = new int[nums.length];
        for (int begin = 1; begin < nums.length; begin++) {
            insert(begin, search(begin, temp), temp, nums);
        }
        return nums;
    }

    private void insert(int source, int dest, int[] array, int[] copy) {
        int value = array[source];
        int copyValue = copy[source];
        for (int i = source; i > dest; i--) {
            array[i] = array[i - 1];
            copy[i] = copy[i - 1];
        }
        array[dest] = value;
        copy[dest] = copyValue;
    }

    private int search(int index, int[] array) {
        int value = array[index];
        int begin = 0, end = index;
        while (begin < end) {
            int mid = (begin + end) >> 1;
            if (value >= array[mid]) {
                begin = mid + 1;
            } else {
                end = mid;
            }
        }
        return begin;
    }
}
